#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MAX_EVENTS 10
#define PORT 8080

int main() {
    int listen_sock, conn_sock, nfds, epollfd;
    struct epoll_event ev, events[MAX_EVENTS];
    struct sockaddr_in addr;

    // 创建socket
    if ((listen_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置socket地址
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(PORT);

    // 绑定socket到地址
    if (bind(listen_sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 监听socket
    if (listen(listen_sock, 5) == -1) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }

    // 创建epoll实例
    if ((epollfd = epoll_create1(0)) == -1) {
        perror("epoll_create1 failed");
        exit(EXIT_FAILURE);
    }

    // 设置要监视的事件：读事件
    ev.events = EPOLLIN;
    ev.data.fd = listen_sock;
    if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == -1) {
        perror("epoll_ctl: listen_sock");
        exit(EXIT_FAILURE);
    }

    for (;;) {
        // 等待事件
        nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
        if (nfds == -1) {
            perror("epoll_wait");
            exit(EXIT_FAILURE);
        }

        // 处理事件
        for (int n = 0; n < nfds; ++n) {
            if (events[n].data.fd == listen_sock) {
                // 处理新的连接
                if ((conn_sock = accept(listen_sock, NULL, NULL)) == -1) {
                    perror("accept");
                    continue;
                }
                printf("Accepted new connection on socket %d\n", conn_sock);

                // 添加新的socket到epoll监视
                ev.events = EPOLLIN;
                ev.data.fd = conn_sock;
                if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &ev) == -1) {
                    perror("epoll_ctl: conn_sock");
                    close(conn_sock);
                }
            } else {
                // 处理已有的连接上的数据
                char buffer[1024];
                ssize_t bytes = recv(events[n].data.fd, buffer, sizeof(buffer), 0);
                if (bytes <= 0) {
                    // 关闭不活跃的连接
                    close(events[n].data.fd);
                    continue;
                }
                buffer[bytes] = '\0';
                printf("Received message: %s\n", buffer);

                // 向客户端发送数据
                send(events[n].data.fd, "Message received", 16, 0);
            }
        }
    }

    // 关闭epoll实例
    close(epollfd);
    close(listen_sock);

    return 0;
}